const App = {
    mixins: [Query],//配置文件，路径/utils/mixins.js
    data() {
        return {
            photo,
            page: {
                activeName: 'first',
                value1: '',
                value2: '',
                PageNumber: 1, //页码
                RowAmount: 10,
                Condition: window.btoa(unescape(encodeURIComponent("%%,%%"))),
                ExtensionCondition: window.btoa(unescape(encodeURIComponent("AND village_project.Village_Number IN (" + getCookie('village') + ")"))),
            },
            form: {},
            showDialog1: false,
            Open_ID: '',
            project_examine_log_attachment: [],
            village_project_category: [],
            str1: '',
            str: '',
            data: [],
            Reason: '',
            fileUrl: '',
            showDialog1: false,
            Project_SerialNumber: '',
            row: {}
        }
    },
    mounted() {

    },
    methods: {
        check() {
            this.page.Condition = window.btoa(unescape(encodeURIComponent("%" + this.page.value1 + "%,%%")));
            this.postgetList(this.page);
        },
        preview(row) {
            this.fileUrl = photo + row.Attachment_URL;
            this.showDialog1 = true;
        },
        async download(row) {
            // if (row.Attachment_URL) {
            //     window.location.href = photo + row.Attachment_URL;
            // }

            let apiUrl = photo + row.Attachment_URL;
            let fileName = apiUrl.split('/').pop();
            try {
                const response = await fetch(apiUrl);
                const blob = await response.blob();
                const url = window.URL.createObjectURL(blob);

                const a = document.createElement('a');
                a.href = url;
                a.download = fileName || 'download';
                document.body.appendChild(a);
                a.click();

                // 清理
                setTimeout(() => {
                    document.body.removeChild(a);
                    window.URL.revokeObjectURL(url);
                }, 100);
            } catch (error) {
                console.error('下载失败:', error);
            }
        },
        handleShow(row) {
            let { primary_key } = JSON.parse(
                document.getElementById("table").getAttribute("data-options")
            );
    
            if (row[primary_key]) {
                window.location.href ="./add.html?action=Modify&nodeKey=" + row[primary_key];
            }

        },
        handlejugong(row) {
            this.$confirm('是否' + (row.Row_Status != '5' ? '竣工' : '取消竣工') + '该数据', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
                let { TableName, primary_key } = JSON.parse(document.getElementById("table").getAttribute("data-options"));
                $.ajax({
                    headers: requestHeaders(),
                    url: `${mh}/generalBusiness/generalQueryByTableNameWithOriginal`,
                    method: "post",
                    data: {
                        Data: TableName,
                        Condition: primary_key + "='" + row[primary_key] + "'"
                    },
                    success: (res) => {
                        if (res.length == 1) {
                            res[0].Row_Status = '5';
                            let lJSONObject_DataSet = new Object();
                            let lJSONObject_Table = new Object();
                            lJSONObject_Table[TableName] = res;
                            lJSONObject_DataSet['Modify'] = lJSONObject_Table;
                            let Operation_Main = JSON.stringify(deepClone(lJSONObject_DataSet));
                            if (!lJSONObject_DataSet['Add']) {
                                lJSONObject_DataSet['Add'] = new Object();
                            }
                            lJSONObject_DataSet['Add']['base_operation_log'] = [{
                                Operation_Type: '0',
                                Operation_Path: this.relativePath,
                                Operation_Main,
                                Operation_Interface: "generalSave",
                                Operation_IP: getIpAddress()
                            }]
                            submitSave(lJSONObject_DataSet, (res) => {
                                if (res.Status == 'success') {
                                    this.postgetList(this.page);
                                    this.seedMessage(row.Open_ID, 'RYsotWoL77G3bv7pXVTKGXFPvhrPRA4bhvtiv5eixT4', {
                                        thing1: { value: row.Village_Project_Category },
                                        date4: { value: getYMDHMSDate(row.Create_Datetime) },
                                        thing2: { value: '竣工' },
                                        thing5: { value: row.Applicant_Name + '项目已竣工' }
                                    });
                                } else {
                                    this.$message({
                                        type: 'error',
                                        message: '操作失败'
                                    });
                                }
                            })
                        } else {
                            this.$message({
                                type: 'error',
                                message: '操作失败'
                            });
                        }

                    }, complete: (XMLHttpRequest) => {

                        requestPretreatment(XMLHttpRequest);
                    }
                });
            }).catch(() => { });
        },
        sumbit(i) {
            this.showDialog = false;
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalQueryByTableNameWithOriginal`,
                method: "post",
                data: {
                    Data: 'village_project',
                    Condition: `Project_SerialNumber='${this.Project_SerialNumber}'`,
                },
                success: (data) => {
                    if (data.length == 1) {
                        data[0].Row_Status = i;
                        data[0].Reason = this.Reason;
                        let lJSONObject_DataSet = {
                            Modify: {
                                village_project: data
                            },
                            Add: {}
                        }
                        let Operation_Main = JSON.stringify(deepClone(lJSONObject_DataSet));
                        lJSONObject_DataSet['Add']['base_operation_log'] = [{
                            Operation_Type: '0',
                            Operation_Path: this.relativePath,
                            Operation_Main,
                            Operation_Interface: "generalSaveByRequestBody",
                            Operation_IP: getIpAddress()
                        }]
                        submitSave(lJSONObject_DataSet, (res) => {
                            if (res.Status == 'success') {
                                this.Reason = '';
                                this.seedMessage(this.Open_ID, 'RYsotWoL77G3bv7pXVTKGXFPvhrPRA4bhvtiv5eixT4', {
                                    thing1: { value: this.row.Village_Project_Category },
                                    date4: { value: getYMDHMSDate(data[0].Create_Datetime) },
                                    thing2: { value: (i == 2 ? '通过' : '拒绝') },
                                    thing5: { value: data[0].Reason ? data[0].Reason : ' ' }
                                });
                                this.postgetList(this.page);
                                this.$message({
                                    message: '操作成功',
                                    type: 'success'
                                });
                            }
                            this.loading = false;
                        })
                    }
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest)
                },
            });
        },
        //消息推送
        seedMessage(openId, templateId, content) {
            $.ajax({
                headers: requestHeaders('JSON'),
                url: `${mh}/requestForward/requestForwardForPost?RequestURL=${encodeURIComponent(`/wx/mp/sendMicroProgramTemplateMessage`)}`,
                method: "POST",
                data: JSON.stringify({ openId, templateId, content }),
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest)
                },
            });
        },
        handlesh(row) {
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalQueryByTableName`,
                method: "post",
                data: {
                    Data: 'village_project_attachment',
                    Condition: `Project_SerialNumber='${row.Project_SerialNumber}' AND Attachment_Type='0'`,
                },
                success: (res) => {
                    this.data = res;
                    this.showDialog = true
                    this.Open_ID = row.Open_ID;
                    this.Project_SerialNumber = row.Project_SerialNumber;
                    this.row = row;
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest)
                },
            });
        },
        Treedata() {
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/clientOperation/getDistrictTree`,
                type: "GET",
                data: {
                    DistrictCode: "232723", //请求参数
                },
                success: (data) => {
                    this.treeData = data;
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json",
            });
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalQueryByTableName`,
                method: "post",
                data: {
                    Data: 'village_project_category',
                    Condition: `Row_Status='0'`,
                },
                success: (res) => {
                    this.village_project_category = res;
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest)
                },
            });
        },
        handleClick() {
            if (this.page.activeName == 'first') {
                this.str1 = '';
            } else if (this.page.activeName == 'second') {
                this.str1 = "\r\nAND village_project.Row_Status = '0'\r\n";
            } else if (this.page.activeName == 'third') {
                this.str1 = "\r\nAND village_project.Row_Status = '2'\r\n";
            } else if (this.page.activeName == 'fourth') {
                this.str1 = "\r\nAND village_project.Row_Status = '3'\r\n";
            }
            this.page.ExtensionCondition = window.btoa(unescape(encodeURIComponent(this.str1 +"AND village_project.Village_Number IN (" + getCookie('village') + ")")));
            this.postgetList(this.page)
        },
        //树的点击筛选事件
        handleNodeClick(data, node) {
            this.page.value2 = data.ProvinceNumber;
            this.page.Condition = window.btoa(unescape(encodeURIComponent("%" + this.page.value1 + "%," + this.page.value2 + "%")));;
            this.postgetList(this.page);
        },
        examine(row) {
            let { primary_key } = JSON.parse(document.getElementById("table").getAttribute("data-options"));
            window.location.href = "./examine.html?action=Modify&nodeKey=" + row[primary_key];
        },
        success(row, res) {
            this.project_examine_log_attachment.push({
                uid: row.uid,
                Attachment_URL: res.fileName,
                Attachment_Name: row.name,
                Temp_Path: res.tempPath,
            })
        },
        remove(row) {
            if (!Object.keys(row).some(item => item.includes('_Original'))) {
                this.project_examine_log_attachment = this.project_examine_log_attachment.filter(i => i.uid != row.uid);
            } else {
                let obj = this.project_examine_log_attachment.filter(i => i.Attachment_SerialNumber == row.Attachment_SerialNumber)[0];
                obj.Row_Status = '1'
            }
        },
        handleRework(row) {
            this.form = row;
            this.showDialog1 = true;
        },
        handleSubmit(row) {
            this.loading = true;
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalQueryByTableNameWithOriginal`,
                method: "post",
                data: {
                    Data: 'project',
                    Condition: `Project_SerialNumber='${row.Project_SerialNumber}'`,
                },
                success: (project) => {
                    project[0].Project_Status = '6';
                    let lJSONObject_DataSet = {
                        Modify: {
                            project
                        },
                        Add: {
                            project_examine_log: [{
                                Project_SerialNumber: row.Project_SerialNumber,
                                Row_Status: '5',
                                Children: {
                                    project_examine_log_attachment: this.project_examine_log_attachment
                                }
                            }]
                        }
                    }
                    let Operation_Main = JSON.stringify(deepClone(lJSONObject_DataSet));
                    lJSONObject_DataSet['Add']['base_operation_log'] = [{
                        Operation_Type: '0',
                        Operation_Path: this.relativePath,
                        Operation_Main,
                        Operation_Interface: "generalSaveByRequestBody",
                        Operation_IP: getIpAddress()
                    }]
                    submitSave(lJSONObject_DataSet, (res) => {
                        if (res.Status == 'success') {
                            this.showDialog1 = false;
                            this.postgetList(this.page);
                        }
                        this.loading = false;
                    })
                    // $.ajax({
                    //     headers: requestHeaders("JSON"),
                    //     url: `${mh}/generalBusiness/generalSaveByRequestBody`,
                    //     method: "post",
                    //     data: JSON.stringify({
                    //         Data: lJSONObject_DataSet,
                    //     }),
                    //     success: (res) => {
                    //         if (res.Status == 'success') {
                    //             this.showDialog1 = false;
                    //             this.postgetList(this.page);
                    //         }
                    //         this.loading = false;
                    //     },
                    //     complete: (XMLHttpRequest) => {
                    //         requestPretreatment(XMLHttpRequest)
                    //     }
                    // });
                },
                complete: (XMLHttpRequest) => {
                    this.loading = false;
                    requestPretreatment(XMLHttpRequest)
                }
            })
        }
    },
};

const { createApp } = Vue;
const app = createApp(App);
//这种方式是引入全部图标，无需单个引入
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    app.component(key, component);
}
app.component('yl-upload', ylUpload);
app.component('yl-online-preview', ylOnlinePreview)
const ElMessage = ElementPlus.ElMessage;
app.use(ElementPlus, { locale: zhCn });
app.mount("#app");
